package cn.edu.sgu.www.mhxysy.service.impl;

import cn.edu.sgu.www.mhxysy.base.Pager;
import cn.edu.sgu.www.mhxysy.dto.RoleAccountDTO;
import cn.edu.sgu.www.mhxysy.entity.RoleAccount;
import cn.edu.sgu.www.mhxysy.exception.GlobalException;
import cn.edu.sgu.www.mhxysy.mapper.RoleAccountMapper;
import cn.edu.sgu.www.mhxysy.restful.ResponseCode;
import cn.edu.sgu.www.mhxysy.service.RoleAccountService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author heyunlin
 * @version 1.0
 */
@Service
public class RoleAccountServiceImpl implements RoleAccountService {

	private final RoleAccountMapper roleAccountMapper;

	@Autowired
	public RoleAccountServiceImpl(RoleAccountMapper roleAccountMapper) {
		this.roleAccountMapper = roleAccountMapper;
	}


	@Override
	public void insert(RoleAccountDTO roleAccountDTO) {
		boolean result = validateBeforeInsert(roleAccountDTO);

		if (result) {
			RoleAccount roleAccount = new RoleAccount();

			roleAccount.setId(roleAccountDTO.getId());
			roleAccount.setName(roleAccountDTO.getName());
			roleAccount.setGrade(roleAccountDTO.getGrade());
			roleAccount.setAccountId(roleAccountDTO.getAccountId());
			roleAccount.setJinbi(roleAccountDTO.getJinbi());
			roleAccount.setScore(roleAccountDTO.getScore());
			roleAccount.setGangId(roleAccountDTO.getGangId());
			roleAccount.setSchoolId(roleAccountDTO.getSchoolId());
			roleAccount.setServerId(roleAccountDTO.getServerId());
			roleAccount.setBirthday(roleAccountDTO.getBirthday());
			roleAccount.setLastUpdateTime(LocalDateTime.now());
			roleAccount.setModelingId(roleAccountDTO.getModelingId());

			roleAccountMapper.insert(roleAccount);
		}
	}

	@Override
	public void deleteById(String roleId) {
		roleAccountMapper.deleteById(roleId);
	}

	@Override
	public void deleteByIds(List<String> ids) {
		if (CollectionUtils.isNotEmpty(ids)) {
			roleAccountMapper.deleteBatchIds(ids);
		}
	}

	@Override
	public void updateById(RoleAccountDTO roleAccountDTO) {
		String accountId = roleAccountDTO.getAccountId();
		String roleId = roleAccountDTO.getId();

		// 根据账号查询角色列表
		QueryWrapper<RoleAccount> wrapper = new QueryWrapper<>();
		wrapper.eq("account_id", accountId);
		List<RoleAccount> list = roleAccountMapper.selectList(wrapper);

		// 如果角色数量达到了6，验证该账号下的角色数量
		if (list.size() == 6) {
			int count = -1;

			// 只要当前角色属于账号下的角色，count就自增1
			for (RoleAccount roleAccount : list) {
				if (roleAccount.getId().equals(roleId)) {
					count ++;
				}
			}

			// count小于0，说明该角色之前不在当前账号下，禁止再次添加
			if (count < 0) {
				throw new GlobalException(ResponseCode.FORBIDDEN, "该账号下已经绑定了6个角色");
			}
		}

		String name = roleAccountDTO.getName();

		// 通过角色名查询
		wrapper = new QueryWrapper<>();
		wrapper.eq("name", name);
		RoleAccount account = roleAccountMapper.selectOne(wrapper);

		// 如果查到的不是当前角色，抛出异常
		if (account != null && !account.getId().equals(roleId)) {
			throw new GlobalException(ResponseCode.CONFLICT, "角色名" + name + "已存在！");
		}

		// 获取角色金币
		Integer jinbi = roleAccountDTO.getJinbi();
		// 修改角色信息
		RoleAccount roleAccount = new RoleAccount();

		roleAccount.setId(roleId);
		roleAccount.setName(name);
		roleAccount.setJinbi(jinbi);
		roleAccount.setAccountId(accountId);
		roleAccount.setGrade(roleAccountDTO.getGrade());
		roleAccount.setScore(roleAccountDTO.getScore());
		roleAccount.setGangId(roleAccountDTO.getGangId());
		roleAccount.setLastUpdateTime(LocalDateTime.now());
		roleAccount.setSchoolId(roleAccountDTO.getSchoolId());
		roleAccount.setServerId(roleAccountDTO.getServerId());
		roleAccount.setBirthday(roleAccountDTO.getBirthday());
		roleAccount.setModelingId(roleAccountDTO.getModelingId());

		roleAccountMapper.updateById(roleAccount);
	}

	@Override
	public List<RoleAccount> selectAll() {
		return roleAccountMapper.selectList(null);
	}

	@Override
	public RoleAccount selectById(String roleId) {
		return roleAccountMapper.selectById(roleId);
	}

	@Override
	public Page<RoleAccount> selectByPage(Pager<RoleAccount> pager) {
		QueryWrapper<RoleAccount> wrapper = Pager.getQueryWrapper(pager, true);
		Page<RoleAccount> page = Pager.ofPage(pager);

		return roleAccountMapper.selectPage(page, wrapper);
	}

	/**
	 * 添加角色之前的验证
	 * @param roleAccountDTO RoleAccountDTO
	 * @return boolean 通过验证返回true，否则抛出异常
	 */
	private boolean validateBeforeInsert(RoleAccountDTO roleAccountDTO) {
		// 1、验证角色名是否重复
		QueryWrapper<RoleAccount> wrapper = new QueryWrapper<>();

		wrapper.eq("name", roleAccountDTO.getName());

		// 通过角色名查询角色数量
		long count = roleAccountMapper.selectCount(wrapper);

		// 角色名重复，抛出异常
		if (count > 0) {
			throw new GlobalException(ResponseCode.CONFLICT, "添加失败，角色名已存在");
		}

		// 2、验证账号下的角色数量是否达到了6
		wrapper = new QueryWrapper<>();

		wrapper.eq("account_id", roleAccountDTO.getAccountId());

		// 通过账号ID查询角色数量
		count = roleAccountMapper.selectCount(wrapper);

		// 角色数量不少于6个，抛出异常
		if (count >= 6) {
			throw new GlobalException(ResponseCode.CONFLICT, "添加失败，每个账号最多可以添加6个角色");
		}

		return true;
	}

}